package com.android.basiclib.core

import android.app.Application
import android.graphics.Color
import android.os.Environment
import android.os.Handler
import com.android.basiclib.BuildConfig
import com.android.basiclib.R
import com.android.basiclib.receiver.ConnectivityReceiver
import com.android.basiclib.utils.CommUtils
import com.android.basiclib.utils.ThreadPoolUtils

import com.android.basiclib.utils.log.MyLogUtils
import com.android.basiclib.utils.log.interceptor.Log2FileInterceptor
import com.android.basiclib.utils.log.interceptor.LogDecorateInterceptor
import com.android.basiclib.utils.log.interceptor.LogPrintInterceptor
import com.android.basiclib.view.gloading.Gloading
import com.android.basiclib.view.gloading.GloadingGlobalAdapter
import com.android.basiclib.view.gloading.GloadingRoatingAdapter
import com.android.basiclib.view.titlebar.EasyTitleBar

import com.hjq.toast.Toaster
import java.io.File

/**
 * 底层的模组依赖库都在这里初始化
 * 当前类在Application中初始化
 */
object BaseLibCore {

    const val successCode = 0   //指定网络请求成功的 Code，一般为 200 或者 0

    /**
     * 初始化全局工具类和图片加载引擎
     */
    fun init(application: Application, handler: Handler?, mainThread: Int) {

        //CommUtil初始化
        CommUtils.init(application, handler, mainThread)

        //初始化全局通用的线程池
        ThreadPoolUtils.init()

        //EaseTitleBar的初始化
        EasyTitleBar.init()
            .backIconRes(R.mipmap.back_black)
            .backgroud(Color.WHITE)
            .titleSize(18)
            .showLine(true)
            .lineHeight(1)
            .menuImgSize(23)
            .menuTextSize(16)
            .lineColor(Color.parseColor("#D2D2D2"))
            .titleColor(Color.BLACK)
            .viewPadding(10)
            .titleBarHeight(48)

        //全局的Loading状态默认配置
        Gloading.initDefault(GloadingGlobalAdapter())

        //吐司框架初始化
        Toaster.init(application)

        //配置Log的拦截器，只有Debug下才生效
        if (BuildConfig.DEBUG) {

            val logPath = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                application.applicationContext.getExternalFilesDir("log")?.absolutePath
                    ?: (application.applicationContext.filesDir.absolutePath + "/log/")
            } else {
                application.applicationContext.filesDir.absolutePath + "/log/"
            }

            val dir = File(logPath)
            if (!dir.exists()) {
                dir.mkdirs()
            }

            MyLogUtils.addInterceptor(LogDecorateInterceptor(true))
            MyLogUtils.addInterceptor(LogPrintInterceptor(true))
            MyLogUtils.addInterceptor(Log2FileInterceptor.getInstance(logPath, true))
        }

    }

    /**
     * 注册网络监听
     */
    fun registerNetworkObserver(application: Application) {
        ConnectivityReceiver.registerReceiver(application)
    }

    fun unregisterNetworkObserver(application: Application) {
        ConnectivityReceiver.unregisterReceiver(application)
    }
}